package com.xzakota.minesweeper.ui.frame;

import com.xzakota.minesweeper.Client;
import com.xzakota.minesweeper.R;
import com.xzakota.minesweeper.controller.Game;
import com.xzakota.minesweeper.controller.GameResource;
import com.xzakota.minesweeper.model.entity.UserBean;
import com.xzakota.minesweeper.msg.*;
import com.xzakota.minesweeper.ui.IWindow;
import com.xzakota.minesweeper.ui.dialog.GameOptionDialog;
import com.xzakota.minesweeper.ui.dialog.templae.OptionDialog;
import com.xzakota.minesweeper.widget.CellLabel;
import com.xzakota.minesweeper.widget.GameCellMapPanel;
import com.xzakota.minesweeper.widget.GameInfoPanel;
import com.xzakota.minesweeper.widget.GameRankListPanel;
import com.xzakota.minesweeper.widget.menu.MultiPlayerGameMenuBar;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

/**
 * 多人游戏界面
 *
 * @author Xzakota
 */
public class MultiPlayerGameFrame extends AbstractBaseFrame {
    private final int currentRoomNum;
    private final List<UserBean> rankUsers;
    private final int level;
    private final Game game;
    private GameRankListPanel rankListPanel;
    private GameInfoPanel controlPanel;

    public MultiPlayerGameFrame(IWindow parent, int currentRoomNum, List<UserBean> rankUsers) {
        super("多人对战");
        this.currentRoomNum = currentRoomNum;
        this.rankUsers = rankUsers;
        this.level = Client.ROOM.get(currentRoomNum).roomLevel;

        game = new Game(this);
        game.gameWinListener.clear();
        game.gameWinListener.add(() -> {
            GameWinMsg gameWinMsg = new GameWinMsg();
            gameWinMsg.data = new Object[] {Client.getClient().currentUser, currentRoomNum, controlPanel.playTime};
            Client.getClient().sendMsg(gameWinMsg);

            new GameOptionDialog("你赢啦, 数据已上传！").showWindow();
        });

        setIconImage(GameResource.getImageResource(R.Image.APP_ICON));
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        CellLabel.loadResource();
        GameInfoPanel.loadResource();

        initLayout();

        MsgHandler handler = msg -> {
            rankUsers.clear();
            rankUsers.addAll(((RoomRankMsg) msg).getRank());
            rankListPanel.updateRankList(rankUsers);
        };
        MsgHandlerFactory.addMsgHandler(MsgHandlerFactory.MSG_TYPE_ROOM_RANK, handler);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                OptionDialog optionDialog = new OptionDialog("是否退出房间？未结束的游戏记录无法保存哦！");
                optionDialog.setConfirmAction(evt -> {
                    optionDialog.closeWindow();
                    Game.dispatchEvent("exitGame");
                });
                optionDialog.showWindow();
            }

            @Override
            public void windowClosed(WindowEvent e) {
                if (parent != null) {
                    parent.showWindow();
                }

                UserExitRoomMsg msg = new UserExitRoomMsg();
                msg.data = new Object[] {Client.getClient().currentUser, MultiPlayerGameFrame.this.currentRoomNum};
                Client.getClient().sendMsg(msg);
                Client.getClient().enterRoomNum = -1;
                MsgHandlerFactory.removeMsgHandler(MsgHandlerFactory.MSG_TYPE_ROOM_RANK, handler);
            }
        });
    }

    public void initLayout() {
        setJMenuBar(new MultiPlayerGameMenuBar(game.model));

        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setBackground(new Color(0xC0CCDA));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));

        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
        leftPanel.setBorder(BorderFactory.createLoweredSoftBevelBorder());
        Dimension preferredSize = leftPanel.getPreferredSize();
        leftPanel.setPreferredSize(new Dimension(
                Math.max(preferredSize.width, 225),
                Math.max(preferredSize.height, Toolkit.getDefaultToolkit().getScreenSize().height * 3 / 4)
        ));

        JTextPane roomTipLabel = new JTextPane();
        roomTipLabel.setEditable(false);
        roomTipLabel.setOpaque(false);
        roomTipLabel.setText("欢迎来到房间 " + currentRoomNum + "，当前为竞速模式" + "\n\n以下为排行榜前十名");
        roomTipLabel.setFont(new Font("黑体", Font.BOLD, 15));
        leftPanel.add(roomTipLabel);

        rankListPanel = new GameRankListPanel(rankUsers);
        leftPanel.add(rankListPanel);

        contentPanel.add(leftPanel, BorderLayout.WEST);

        JPanel rightPanel = new JPanel(new BorderLayout());

        controlPanel = new GameInfoPanel(game.model);
        rightPanel.add(controlPanel, BorderLayout.SOUTH);

        GameCellMapPanel minePanel = new GameCellMapPanel(game.model);
        rightPanel.add(minePanel, BorderLayout.CENTER);

        contentPanel.add(rightPanel, BorderLayout.EAST);

        setContentPane(contentPanel);
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension preferredSize = super.getPreferredSize();

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        return new Dimension(
                Math.min(preferredSize.width, screenSize.width),
                Math.min(preferredSize.height, screenSize.height * 2 / 3)
        );
    }

    @Override
    public void showWindow() {
        if (level == 1) {
            game.setBasicLevel();
        } else if (level == 2) {
            game.setIntermediateLevel();
        } else if (level == 3) {
            game.setExpenseLevel();
        }
        updateUI();

        super.showWindow();
    }
}
